<template>
	<view>
		<!-- 头部背景 -->
		<view class="headCss"></view>

		<!-- 控制面板 -->
		<view class="headText">
			<view class="input-group">
				<view class="label">
					负责人:
				</view>
				<input class="input-border" v-model="formData.responsiblePerson" type="text" placeholder="输入责任人姓名" />
			</view>
			<view class="input-group">
				<view class="label">
					身份证号码:
				</view>
				<input class="input-border" v-model="formData.idCard" type="number" placeholder="输入负责人身份证号码" />
			</view>
			<view class="input-group">
				<view class="label">
					手机号:
				</view>
				<input class="input-border" v-model="formData.phone" type="tel" placeholder="输入手机号" />
			</view>
			<view class="input-group">
				<view class="label">
					验证码:
				</view>
				<input class="input-border" v-model="formData.verifyCode"
					style="width: 150rpx; border-radius: 4rpx 0rpx 0rpx 4rpx;" type="text" placeholder="输入验证码" />
				<view class="input-border" @click="getCode()"
					style="width: 156rpx; color: #3385fd; background-color: #F5F5F5; border-radius: 0rpx 4rpx 4rpx 0rpx;">
					获取验证码
				</view>
			</view>

			<view class="input-group">
				<view class="label">
					店名:
				</view>
				<input class="input-border" v-model="formData.storeName" type="text" placeholder="输入责任人姓名" />
			</view>
			<view class="input-group">
				<view class="label">
					工商营业执照号码:
				</view>
				<input class="input-border" v-model="formData.businessLicense" type="text" placeholder="输入营业执照号码" />
			</view>
			<view class="input-group">
				<view class="label">
					经营区域:
				</view>
				<view style="width: 390rpx;">
					<uni-data-picker placeholder="经营区域" popup-title="请选择所在地区" :localdata="dataTree" v-model="classes"
						@change="onchange" @nodeclick="onnodeclick" @popupopened="onpopupopened"
						@popupclosed="onpopupclosed">
					</uni-data-picker>
				</view>
			</view>
			<view class="input-group">
				<view class="label">
					地址:
				</view>
				<input class="input-border" v-model="formData.address" type="text" placeholder="输入详细地址" />
			</view>
		</view>

		<view class="headText" style="margin-top: 20rpx;">
			<view class="text1">
				商家简介
			</view>
			<textarea class="text2" v-model="formData.introduction" name="" id="" cols="30" rows="10"
				placeholder="请准确的介绍一下公司的情况"></textarea>
		</view>

		<view class="headText" style="margin-top: 20rpx;">
			<view class="text1">
				身份证正反照片
			</view>
			<view style="display: flex;  align-items: center;">
				<view class="img" @click="toCamera('idCardFront')" v-if="formData.idCardFront==''">
					<image src="/static/images/加号.png" mode=""></image>
					<view>人像面</view>
				</view>
				<view class="img" v-else>
					<image :src="formData.idCardFront" style="width: 150rpx; height: 150rpx; margin-top: 10rpx;">
					</image>
				</view>

				<view class="img" @click="toCamera('idCardBack')" v-if="formData.idCardBack==''">
					<image src="/static/images/加号.png" mode=""></image>
					<view>国徽面</view>
				</view>
				<view class="img" v-else>
					<image :src="formData.idCardBack" style="width: 150rpx; height: 150rpx; margin-top: 10rpx;"></image>
				</view>

			</view>
		</view>


		<view class="headText" style="margin-top: 20rpx;">
			<view class="text1">
				营业执照
			</view>
			<view style="display: flex;  align-items: center;">
				<view class="img" @click="toCamera('businessLicenseImg')" v-if="formData.businessLicenseImg==''">
					<image src="/static/images/加号.png" mode=""></image>
					<view>上传照片</view>
				</view>
				<view class="img" v-else>
					<image :src="formData.businessLicenseImg" style="width: 150rpx; height: 150rpx; margin-top: 10rpx;">
					</image>
				</view>
			</view>
		</view>

		<view class="headText" style="margin-top: 20rpx;">
			<view class="text1">
				门店照片
			</view>
			<view style="display: flex;  align-items: center;">
				<view class="img" @click="toCamera('storeImg')" v-if="formData.storeImg==''">
					<image src="/static/images/加号.png" mode=""></image>
					<view>上传照片</view>
				</view>
				<view class="img" v-else>
					<image :src="formData.storeImg" style="width: 150rpx; height: 150rpx; margin-top: 10rpx;"></image>
				</view>
			</view>
		</view>

		<button type="primary" style="width: 70%; border-radius: 40rpx; margin-top: 40rpx;"
			@click="toRegister()">注册</button>
		<view style="width: 100rpx; height: 200rpx;" />

	</view>
</template>

<script>
	import address from '@/static/data/city-data.json';
	import {
		get,
		post
	} from '@/utils/request.js';
	export default {
		data() {
			return {
				formData: {
					responsiblePerson: '', // 负责人
					idCard: '', // 身份证
					phone: '', // 电话
					verifyCode: '', // 验证码
					storeName: '', // 店铺名称
					businessLicense: '', // 营业执照号码
					region: '', // 地区
					address: '', // 地址
					introduction: '', // 简介
					idCardFront: '', // 身份证正面
					idCardBack: '', // 身份证反面
					businessLicenseImg: '', // 营业执照图片
					storeImg: '' // 门店图片
				},
				classes: '',
				dataTree: address,
				isShowCode: true, // 验证码按钮是否可用
				countdown: 60, // 倒计时秒数



			};
		},
		onLoad() {

		},
		methods: {
			// 上传到服务器
			uploadToServer(tempFilePath, e) {
				// 显示加载中
				uni.showLoading({
					title: '上传中...'
				});

				// 2. 调用上传 API
				uni.uploadFile({

					url: 'http://localhost:8080/file/upload', // 后端接收文件的接口
					filePath: tempFilePath, // 临时文件路径
					name: 'file', // 后端接收文件的参数名（需与后端一致）
					header: {
						"Authorization": "Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6ImVmNzI5M2UxLWY1ZmEtNGQ2OC04NjNjLWJmZGUwYzMzYTU2OCIsInVzZXJuYW1lIjoiYWRtaW4ifQ.9X3S8BpLghKQrIrw8r4RzpdFNjv735vZjvKHYYrRCuwWdo2ChKanCaPiOTH8rSMHbLkBNqJeXlmBnvMvDT2mCA"
					},
					formData: {},
					success: (uploadRes) => {
						// 上传成功，解析后端返回的结果
						const result = JSON.parse(uploadRes.data);
						if (result.code === 200) {
							uni.showToast({
								title: '上传成功',
								icon: 'success'
							});
							var url = result.data.url
							console.log("图片地址：", url);
							// idCardFront: '',
							// idCardBack: '',
							// businessLicenseImg: '',
							// storeImg: ''
							if (e === 'idCardFront') {
								// 身份证人像面
								this.formData.idCardFront = url
							} else if (e === 'idCardBack') {
								// 身份证 国徽面
								this.formData.idCardBack = url
							} else if (e === 'businessLicenseImg') {
								// 营业执照
								this.formData.businessLicenseImg = url
							} else if (e === 'storeImg') {
								// 门店图片
								this.formData.storeImg = url
							}
						} else {
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('上传失败：', err);
						uni.showToast({
							title: '网络错误',
							icon: 'none'
						});
					},
					complete: () => {
						// 无论成功失败，都关闭加载
						uni.hideLoading();
					}
				});
			},
			toCamera(e) {
				// 调用 选择图片
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera '], //从相册选择
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0]
						this.uploadToServer(tempFilePath, e)
					}
				});
			},
			onnodeclick(e) {
				// console.log(e);
			},
			onpopupopened(e) {
				// console.log('popupopened');
			},
			onpopupclosed(e) {
				// console.log('popupclosed');
			},
			onchange(e) {
				console.log('onchange:', e);
				var region = ''
				for (var i = 0; i < e.detail.value.length; i++) {
					region += e.detail.value[i].text
				}
				// console.log('region',region);
				this.formData.region = region
			},


			// 表单验证方法
			validateForm(formData) {
				// 非空验证的字段列表
				const requiredFields = [{
						key: 'responsiblePerson',
						name: '负责人'
					},
					{
						key: 'idCard',
						name: '身份证'
					},
					{
						key: 'phone',
						name: '电话'
					},
					{
						key: 'verifyCode',
						name: '验证码'
					},
					{
						key: 'storeName',
						name: '店铺名称'
					},
					{
						key: 'businessLicense',
						name: '营业执照号码'
					},
					{
						key: 'region',
						name: '地区'
					},
					{
						key: 'address',
						name: '地址'
					},
					{
						key: 'introduction',
						name: '简介'
					},
					{
						key: 'idCardFront',
						name: '身份证正面图片'
					},
					{
						key: 'idCardBack',
						name: '身份证反面图片'
					},
					{
						key: 'businessLicenseImg',
						name: '营业执照图片'
					},
					{
						key: 'storeImg',
						name: '门店图片'
					}
				];

				// 检查所有必填字段是否为空
				for (const field of requiredFields) {
					if (!formData[field.key] || formData[field.key].trim() === '') {
						uni.showToast({
							title: `${field.name}不能为空`,
							icon: 'none',
							duration: 2000
						});
						return false;
					}
				}

				// 身份证格式验证 (18位)
				const idCardReg = /(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
				if (!idCardReg.test(formData.idCard)) {
					uni.showToast({
						title: '请输入正确的身份证号码',
						icon: 'none',
						duration: 2000
					});
					return false;
				}

				// 手机号格式验证 (11位数字)
				const phoneReg = /^1[3-9]\d{9}$/;
				if (!phoneReg.test(formData.phone)) {
					uni.showToast({
						title: '请输入正确的手机号码',
						icon: 'none',
						duration: 2000
					});
					return false;
				}

				// 验证码格式验证 (假设为6位数字)
				const codeReg = /^\d{6}$/;
				if (!codeReg.test(formData.verifyCode)) {
					uni.showToast({
						title: '请输入6位数字验证码',
						icon: 'none',
						duration: 2000
					});
					return false;
				}

				// 营业执照号码验证 (假设为15-18位数字或字母)
				const licenseReg = /^[A-Za-z0-9]{15,18}$/;
				if (!licenseReg.test(formData.businessLicense)) {
					uni.showToast({
						title: '请输入正确的营业执照号码',
						icon: 'none',
						duration: 2000
					});
					return false;
				}

				// 所有验证通过
				return true;
			},
			getCode() {
				// 验证手机号是否正确（可复用之前的手机号验证逻辑）
				const phoneReg = /^1[3-9]\d{9}$/;
				if (!phoneReg.test(this.formData.phone)) {
					uni.showToast({
						title: '请输入正确的手机号码',
						icon: 'none',
						duration: 2000
					});
					return;
				}

				// 当isShowCode为true时才发起请求
				if (this.isShowCode) {
					// 调用后端接口获取验证码
					get("/auth/code2", {
						"username": this.formData.phone
					}).then(resp => {
						console.log(resp);
						if (resp.code === 200) {
							uni.showToast({
								title: resp.msg + "：" + resp.data,
								icon: 'success',
								duration: 15000
							});
						} else {
							uni.showToast({
								title: resp.msg,
								icon: 'error',
								duration: 2000
							});
						}
						this.isShowCode = false;
						// 启动倒计时定时器
						const timer = setInterval(() => {
							this.countdown--;

							// 倒计时结束，恢复初始状态
							if (this.countdown <= 0) {
								clearInterval(timer);
								this.isShowCode = true;
								this.countdown = 60; // 重置倒计时
							}
						}, 1000);
					}).catch(err => {
						console.log("err", err);
					});
				} else {
					// 当isShowCode为false时，提示用户倒计时信息
					uni.showToast({
						title: `请于${this.countdown}秒后再次点击`,
						icon: 'none',
						duration: 1500
					});
				}
			},


			// 注册
			toRegister() {
				
				if (this.validateForm(this.formData)) {
					// 验证通过，执行提交逻辑
					console.log('表单验证通过，可以提交');
					console.log(this.formData);
					
					
					post("/auth/register1",this.formData).then(resp=>{
						console.log(resp);
					})
				}
			}
		}
	};
</script>

<style scoped>
	.headCss {
		background-color: #3385fd;
		width: 750rpx;
		height: 300rpx;
		position: fixed;
	}

	.headText {
		background-color: #fff;
		border-radius: 20rpx;
		width: 710rpx;
		/* height: 80vh; */
		margin-left: 20rpx;
		position: relative;
		padding-bottom: 40rpx;
	}

	.input-group {
		padding: 20rpx;
		display: flex;
		/* justify-content: center; */
		align-items: center;
		width: 100%;
	}

	.label {
		width: 280rpx;
		font-weight: 500;
		font-size: 32rpx;
		/* border: 1rpx solid red; */
	}

	.input-border {
		width: 350rpx;
		border: 1rpx solid #d1d1d1;
		border-radius: 4rpx;
		padding: 20rpx 20rpx;
	}

	.text1 {
		padding: 20rpx;
		font-size: 32rpx;
		font-weight: 500;
	}

	.text2 {
		width: 610rpx;
		margin-left: 20rpx;
		border: 1rpx solid #d1d1d1;
		border-radius: 30rpx;
		padding: 20rpx 30rpx;
	}

	.input-group:last-child {
		padding-bottom: 0rpx;
	}

	.img {
		border: 1rpx solid #d1d1d1;
		border-radius: 10rpx;
		width: 180rpx;
		height: 180rpx;
		text-align: center;
		color: #d1d1d1;
		font-size: small;
		margin-left: 20rpx;
	}

	.img>image {
		margin-top: 50rpx;
		width: 30rpx;
		height: 30rpx;
		margin-bottom: 20rpx;
	}

	::-webkit-scrollbar {
		display: none;
	}
</style>